import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpSever {
    private DatagramSocket socket = null;
    public UdpSever(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("UdpSever启动！");
        while(true){
            DatagramPacket requestPocket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPocket);
            String request = new String(requestPocket.getData(),0,requestPocket.getLength());
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes()
                    ,response.getBytes().length,requestPocket.getSocketAddress());
            socket.send(responsePacket);
            //打印日志
            System.out.printf("[%s : %d] req: %s res: %s\n",requestPocket.getAddress().toString(),
                    requestPocket.getPort(),request,response);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpSever udpSever = new UdpSever(9090);
        udpSever.start();
    }
}
